var replaceUpload = -1;

$(window).addEvents({ /*{{{*/
    'domready':function(){
        //解析子目录并进行显示
        var span=$('dirlist');
        var subdirs=subdir.split(/[\\|\/]/g);
        var path='',foldername;
        for(var i=0,len=subdirs.length;i<len;i++){
            foldername=subdirs[i];
            path+=foldername+'/';
            if(!foldername) continue;
            span.grab(new Element('label',{
                'html':foldername,
                'title':'{$rootName}'+path,
                '_subdir':path,
                'events':{
                    'click':function(){
                        godir(this.getProperty('_subdir'),true);
                    }
                }
            }));
        }
        //绑定上传效果
        var ubtn=$('uploadImgSpan');
        var up=new Swiff.Uploader({
            url:URL+'/save',
            multiple:false,
            appendCookieData:true,
            path:TMPL+'fancyupload/Swiff.Uploader.swf',
            data:{'root':rootdir,'subdir':subdir},
            instantStart:false,
            target:ubtn,
            onFileComplete:function(file){
                var json=JSON.decode(file.response.text);
                var ret=json.data;
                if(!ret || ret.error){
                    top.showMsg(ret.name+top.Lang['js_media_upload_fail'],{disappear:2,type:'failure'});
                }else{
                    top.showMsg(ret.name+top.Lang['js_media_upload_ok'],{disappear:1});
                    if(replaceUpload != -1){
                        //覆盖上传，只需修改原来的文件信息即可
                        var tr = $('fileTR'+replaceUpload),tds = tr.getChildren();
                        tds[2].set('html',ret.mtime);
                        tds[3].set('html',ret.size);
                    }else{
                        reloadPage();
                    }
                    replaceUpload = -1;
                }
                file.remove();
            },
            onFileProgress:function(file){
                //console.info(this.uploading+'    '+this.rate+'   '+this.size+'    '+this.bytesLoaded);
            },
            onSelectSuccess:function(files){
                //检查是否有同名文件名上传
                var id = flHash.keyOf(files[0].name);
                if(id){
                     if(!window.confirm(top.Lang['js_media_replacefile'])){
                         return false;
                     }else{
                         replaceUpload = id;
                     }
                }
                up.start(); //开始上传
            },
            onFail:function(errorType){
                alert(top.Lang['js_media_upload_fail']+':'+errorType);
            }
        });
        ubtn.addEvents({
        });
    }
});/*}}}*/

function getHashId(aobj){
    var tr = aobj.getParent().getParent();
    return tr.getProperty('id').substr(6);
}
function getHashVal(aobj){
    var id = getHashId(aobj);
    if(flHash.has(id)){
        return flHash.get(id);
    }else{
        return '';
    }
}

function godir(path,direct){
    var fm=document.forms['explorerForm'];
    var subdirHidden=fm.elements['subdir'];
    subdirHidden.value=(direct || false) ? path : (subdir+path);
    fm.elements['a'].value='index';
    fm.submit();
}
function jumpRoot(root){
    var fm=document.forms['explorerForm'];
    fm.elements['subdir'].value='';
    fm.elements['root'].value=root;
    fm.elements['a'].value='index';
    fm.submit();
}
function deleteFile(aobj){
    var fm = $(document.forms['explorerForm']);
    fm.elements['a'].value = 'removal';
    var filename = getHashVal(aobj);
    fm.elements['filename'].value = filename;
    fm.elements['subdir'].value = subdir;

    var ajax = new Request.JSON({
        url:URL+'/removal',
        data:fm.toQueryString(),
        onSuccess:function(json){
            if(json.status==1){    //删除成功
                top.showMsg(top.Lang['js_media_file_removal_ok'].replace('%s',filename),{disappear:1});
                flHash.erase(getHashId(aobj));  //从hash中删除掉指定的值
                $(aobj.parentNode.parentNode).destroy();    //移除文件对应的行
            }else{
                top.showMsg(top.Lang['js_media_file_removal_fail'].replace('%s',filename),{disappear:1});
            }
        }
    });
    ajax.send();
}
function renameFile(){
    var val=top.yaModal.prompt({
        'message':top.Lang['js_media_type_file_rename'],
        'title':top.Lang['js_media_title_file_rename'],
        'onReturn':function(val,imputObj){
            if(!/^[^\\/:\*\?"<>\|]*$/.test(val)){
                alert(top.Lang['js_media_filename_unvalid']);
                return false;
            }
            var fm = document.forms['explorerForm'];
            fm.elements['filename'].value = val;
            var ajax = new Request.JSON({
                url:URL+'/createDirectory',
                data:fm.toQueryString(),
                onSuccess:function(json){
                    if(json.status==1){    //删除成功
                        top.showMsg(top.Lang['js_media_createdir_ok'],{disappear:1});
                        reloadPage();
                    }else{
                        top.showMsg(top.Lang['js_media_createdir_fail'],{disappear:1});
                    }
                }
            });
            ajax.send();
        }
    });
}

function create_directory(){
    var val=top.yaModal.prompt({
        'message':top.Lang['js_media_type_dirname'],
        'title':top.Lang['js_media_title_createdir'],
        'onReturn':function(val,imputObj){
            if(!/^[^\\/:\*\?"<>\|]*$/.test(val)){
                alert(top.Lang['js_media_filename_unvalid']);
                return false;
            }
            var fm = document.forms['explorerForm'];
            fm.elements['filename'].value = val;
            var ajax = new Request.JSON({
                url:URL+'/createDirectory',
                data:fm.toQueryString(),
                onSuccess:function(json){
                    if(json.status==1){    //删除成功
                        top.showMsg(top.Lang['js_media_createdir_ok'],{disappear:1});
                        reloadPage();
                    }else{
                        top.showMsg(top.Lang['js_media_createdir_fail'],{disappear:1});
                    }
                }
            });
            ajax.send();
        }
    });
}

function reloadPage(){
    var fm = document.forms['explorerForm'];
    fm.elements['a'].value= 'index';
    fm.submit();
}